
//
//  KYSportTracking.m
//  kyysprot
//
//  Created by HongYi on 2017/7/1.
//  Copyright © 2017年 kcvly. All rights reserved.
//

#import "KYSportTracking.h"

#import "KYSportTrackingLine.h"

@interface KYSportTracking ()
@property (nonatomic, strong) NSMutableArray *trackingLines;

@end

@implementation KYSportTracking {
    CLLocation *_startLocation;
}

- (instancetype)initWithType:(KYSportType)sportType {
    if (self = [super init]) {
        _sportType = sportType;
        self.sportState = KYSportStateContinue;
    }
    return self;
}

- (UIImage *)sportIcon {
    NSString *iconName = @"";
    switch (self.sportType) {
        case KYSportTypeWalk:
            iconName = @"map_annotation_walk";
            break;
        case KYSportTypeRun:
            iconName = @"map_annotation_run";
            break;
        case KYSportTypeBike:
            iconName = @"map_annotation_bike";
            break;
    }
    return [UIImage imageNamed:iconName];
}

- (MAPolyline *)polyLineWithLocation:(CLLocation *)location color:(UIColor *)color {
    if (KYSportStateContinue != self.sportState) {
        _startLocation = nil;
        return nil;
    }
    
    if (location.speed <= 0) {
        return nil;
    }
    
    // 判断定位的时间差值，暂时定义一个时间差值因子 - 性能优化（避免室内出现杂线）
    CGFloat factor = 2;
    if ([[NSDate date] timeIntervalSinceDate:location.timestamp] > factor) {
        // 如果超过时间差值，就认为定位的精度不够
        return nil;
    }
    
    if (nil == _startLocation) {
        _startLocation = location;
        return nil;
    }
    
    KYSportTrackingLine *sportTrackingLine = [[KYSportTrackingLine alloc] initWithStartLocation:_startLocation endLocation:location];
    [self.trackingLines addObject:sportTrackingLine];
    _startLocation = location;
    NSLog(@"====> 总耗时: %.2fs 总距离: %.2fkm 平均速度: %.2fkm/h 最大速度: %.2fkm/h", self.totalTime, self.totalDistance, self.avgSpeed, self.maxSpeed);
    return sportTrackingLine.polyline;
}

- (double)avgSpeed {
    return [[self.trackingLines valueForKeyPath:@"@avg.speed"] doubleValue];
}

- (double)totalTime {
    return [[self.trackingLines valueForKeyPath:@"@sum.time"] doubleValue];
}

- (double)totalDistance {
    return [[self.trackingLines valueForKeyPath:@"@sum.distance"] doubleValue];
}

- (double)maxSpeed {
    return [[self.trackingLines valueForKeyPath:@"@max.speed"] doubleValue];
}

- (NSMutableArray *)trackingLines {
    if (nil == _trackingLines) {
        _trackingLines = [NSMutableArray array];
    }
    return _trackingLines;
}

@end
